﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;
using System.Linq;

namespace Common.Quartz
{
    /// <summary>
    /// Quartz扩展
    /// </summary>
    public static class QuartzExtenstion
    {
        /// <summary>
        /// 注册Quartz服务
        /// </summary>
        /// <param name="services"></param>
        public static void AddQuartzTask(this IServiceCollection services)
        {
            //注册Quartz服务
            services.AddQuartzServer(options =>
            {
                //是否等待任务完成
                options.WaitForJobsToComplete = true;
            });

            //注册调度工厂
            services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();

            //注册自定义任务工厂
            services.AddSingleton<IJobFactory, IOCJobFactory>();

            //注册Quartz启动服务
            services.AddSingleton<QuartzStartup>();

            //注册任务
            var jobList = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(x => x.GetTypes().Where(i => i.GetInterfaces().Contains(typeof(IJob))))
                .ToList();
            foreach (var item in jobList)
            {
                services.AddTransient(item);
            }
        }

        /// <summary>
        /// 启动Quartz服务
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseQuartzTask(this IApplicationBuilder app)
        {
            //获取注入的Quartz启动服务并启动服务
            //var quartzStart = app.ApplicationServices.GetRequiredService<QuartzStartup>();
            //quartzStart.StartAsync().Wait();
            app.ApplicationServices.GetRequiredService<QuartzStartup>().StartAsync().Wait();
            return app;
        }
    }
}
